//
//  NewEntryViewController.swift
//  test
//
//  Created by george on 12/23/15.
//  Copyright © 2015 test. All rights reserved.
//

import UIKit
import CoreData

enum NewEntryTask {
	case Sale
	case Rent
}

class NewEntryViewController: UIViewController {

	var task: NewEntryTask?
	var titleF = UITextField()
	var contentF = UITextField()
	var addB = UIButton(type: .System)

	override func viewDidLoad() {
		super.viewDidLoad()
		view.backgroundColor = UIColor.whiteColor()

		view.addSubview(titleF)
		titleF.placeholder = "title"
		view.addSubview(contentF)
		contentF.placeholder = "content"
		view.addSubview(addB)
		addB.backgroundColor = UIColor.redColor()
		addB.addTarget(self, action: "new", forControlEvents: .TouchUpInside)

		self.edgesForExtendedLayout = UIRectEdge.None
	}

	override func viewWillLayoutSubviews() {
		super.viewWillLayoutSubviews()

		titleF.translatesAutoresizingMaskIntoConstraints = false
		view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[title]", options: .AlignAllBaseline, metrics: nil, views: ["title":titleF]))
		view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[title]-|", options: .AlignAllBaseline, metrics: nil, views: ["title":titleF]))

		contentF.translatesAutoresizingMaskIntoConstraints = false
		view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[title]-[content(>=80)]", options: .AlignAllCenterX, metrics: nil, views: ["title":titleF, "content":contentF]))
		view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[content]-|", options: .AlignAllBaseline, metrics: nil, views: ["content":contentF]))

		addB.translatesAutoresizingMaskIntoConstraints = false
		view.addConstraint(NSLayoutConstraint(item: addB, attribute: .Top, relatedBy: .GreaterThanOrEqual, toItem: contentF, attribute: .Bottom, multiplier: 1, constant: 10))
		view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[button]-|", options: .AlignAllCenterX, metrics: nil, views: ["button": addB]))
	}

	func new() {
		let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
		let moc = delegate.privateMOC

		let house = NSEntityDescription.insertNewObjectForEntityForName("House", inManagedObjectContext: moc) as! House
		house.city = "Chengdu"
		house.id = random()

		switch self.task! {
		case .Sale:
			let sale = NSEntityDescription.insertNewObjectForEntityForName("Sale", inManagedObjectContext: moc) as! Sale
			sale.title = self.titleF.text!
			sale.content = self.contentF.text!
			sale.house = house
			sale.manager = self.currentManager(moc)
			moc.insertObject(sale)
		case .Rent:
			let rent = NSEntityDescription.insertNewObjectForEntityForName("Rent", inManagedObjectContext: moc) as! Rent
			rent.title = self.titleF.text!
			rent.content = self.contentF.text!
			rent.house = house
			rent.manager = self.currentManager(moc)
			moc.insertObject(rent)
		}
		do {
			try moc.save()
		} catch {
			print(error)
		}

		self.dismissViewControllerAnimated(true, completion: nil)
	}

	func currentManager(moc: NSManagedObjectContext) -> Manager {
		let manager_id = 1

		let managerFetcher = NSFetchRequest(entityName: "Manager")
		managerFetcher.predicate = NSPredicate(format: "id == %@", argumentArray: [manager_id])
		do {
			let results = try moc.executeFetchRequest(managerFetcher)
			if let manager = results.first as! Manager? {
				return manager
			} else {
				let manager = NSEntityDescription.insertNewObjectForEntityForName("Manager", inManagedObjectContext: moc) as! Manager
				manager.id = manager_id
				manager.name = "George"
				moc.insertObject(manager)
				return manager
			}
		} catch {
			fatalError("WRONG")
		}
	}

}
